package com.szit.test.filter;

import com.szit.test.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter",urlPatterns = "/sys/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 过滤器初始化
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 示例：检查用户是否拥有特定角色
        User loginUser = (User) httpRequest.getSession().getAttribute("loginUser");

        // if ("admin".equals(userRole)) {
        if(loginUser != null) {
            // 如果已经登录，则允许访问，调用下一个过滤器
            chain.doFilter(request, response);
        } else {
            // 如果未登录，则跳到登录提示页面
            // httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
            httpResponse.sendRedirect(httpRequest.getContextPath()+"/loginerror.jsp");
        }
    }

    @Override
    public void destroy() {
        // 过滤器销毁
    }
}